package com.yimi.yinhepda.views.sign_manager;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.JiaoJianAdapter;
import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.base.BaseTitleActivity;
import com.yimi.yinhepda.callbacks.QueryMacUICallBack;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.BreakCardTableDao;
import com.yimi.yinhepda.db.table.BreakCardTable;
import com.yimi.yinhepda.entity.request.BreakCardRequest;
import com.yimi.yinhepda.entity.response.JiaoJianBreakCardResponse;
import com.yimi.yinhepda.entity.response.QueryJiaoJianStowagesResponse;
import com.yimi.yinhepda.entity.sign_manager.JiaoJianBreakCardEntity;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.net.QueryMacNetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.uce.commom.util.LogUtil;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.NetworkUtil;
import com.pda.ym.utils.SoundVibratorManager;

import org.jetbrains.annotations.NotNull;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 网点交件到达打卡界面
 *
 * @author 000432
 * @date 2018/6/1 0001
 */

public class JiaoJianBreakCardActivity extends BaseTitleActivity implements CommonViewHolder.onItemCommonClickListener {

    private RecyclerView mJiaojianViewList;
    private JiaoJianAdapter mAdapter;
    private List<JiaoJianBreakCardEntity> mStowagesEntities;
    private JiaoJianBreakCardEntity checkBreakCardEntity;
    private BreakCardTableDao breakCardTableDao;
    /**
     * 1-交件打卡
     */
    private final int CLOCK_TYPT = 1;

    @Override
    public String getPageName() {
        return "网点交件到达打卡";
    }

    @Override
    public int setContentViewId() {
        return R.layout.activity_jiaojian_break_card;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();
        initData();
    }

    private void initView() {
        findViewById(R.id.ib_back).setOnClickListener(this);
        findViewById(R.id.btn_reFresh).setOnClickListener(this);
        findViewById(R.id.btn_break_card).setOnClickListener(this);
        mJiaojianViewList = findViewById(R.id.rv_jiaojian_list);
    }

    private void initData() {
        breakCardTableDao = new BreakCardTableDao();
        mStowagesEntities = new ArrayList<>();
        mAdapter = new JiaoJianAdapter(this, mStowagesEntities, this);
        mJiaojianViewList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mJiaojianViewList.setAdapter(mAdapter);
        loadData();
    }

    private void loadData() {
        showPgDlg("加载数据中...");
        String url = "";
        if (Common.BREAK_CARD_SWITCH == 1) {
            //旧打卡接口
            url = Constants.URL_CAR_CLOCK_FIND_STOWAGES;
        } else {
            //新打卡接口
            url = Constants.URL_QUERY_VMS_FINDSTOWAGES;
        }
        Map<String, String> params = new HashMap<>(2);
        //打开类型：1-交件 2-接件 3-离港 4-靠台 5-出发 6-到达
        params.put("clockType", CLOCK_TYPT + "");
        params.put("deptCode", sharedPreferUtil.getDeptCode());
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(url)
                .setParams(params)
                .setResponsClazz(QueryJiaoJianStowagesResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        if (obj instanceof QueryJiaoJianStowagesResponse) {
                            QueryJiaoJianStowagesResponse response = (QueryJiaoJianStowagesResponse) obj;
                            mStowagesEntities.clear();
                            for (JiaoJianBreakCardEntity entity : response.getData()) {
                                //查询本地已打卡数据
                                BreakCardTable breakCardTable =
                                        breakCardTableDao.getDate(entity.getStowageNo(), sharedPreferUtil.getWorkNum(), CLOCK_TYPT, sharedPreferUtil.getDeptCode());
                                if (breakCardTable != null) {
                                    entity.setBreakTime(breakCardTable.getClockTime());
                                    entity.setTimeSeq(breakCardTable.getTimeSeq());
                                    entity.setBreakDate(breakCardTable.getClockDate());
                                }
                                mStowagesEntities.add(entity);
                            }
                            //按照时间降序
                            Collections.sort(mStowagesEntities);
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                });

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ib_back:
                finish();
                break;
            case R.id.btn_reFresh:
                loadData();
                break;
            case R.id.btn_break_card:
                //打卡按钮
                if (checkBreakCardEntity == null || !checkBreakCardEntity.isCheck()) {
                    showToast("请先选择一项数据！");
                    return;
                }
                MyDialog dialog = new MyDialog(this);
                dialog.setIcon(R.drawable.alert);
                dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                dialog.setTitle("提示");
                dialog.setMessage("是否确定打卡？");
                dialog.setPositiveClickListener( "是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        checkAPMacEnable();
                    }
                });
                dialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", null);
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClickListener(int position) {
        if (position == RecyclerView.NO_POSITION) {
            return;
        }
        checkBreakCardEntity = mStowagesEntities.get(position);
        if (checkBreakCardEntity.isCheck()) {
            checkBreakCardEntity.setCheck(false);
        } else {
            for (JiaoJianBreakCardEntity entity : mStowagesEntities) {
                entity.setCheck(false);
            }
            checkBreakCardEntity.setCheck(true);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemLongClickListener(int position) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            //获取当前时间戳
            Long currTime = DateHelper.getTimeStamp();
            List<BreakCardTable> breakCardTables = breakCardTableDao.getDates(sharedPreferUtil.getWorkNum(), CLOCK_TYPT, sharedPreferUtil.getDeptCode());
            if (breakCardTables != null) {
                for (BreakCardTable entity : breakCardTables) {
                    Date date = DateHelper.StrToDate(entity.getClockDateTime(), DateHelper.timeFormat);
                    Long diffTime = currTime - date.getTime();
                    if (diffTime > 1000 * 60 * 60 * 24 * 3) {
                        //删除大于三天的配载单
                        breakCardTableDao.delete(breakCardTables);
                    }
                }
            }
        } catch (SQLException e) {
            LogUtil.e(e.toString());
        }
    }

    /**
     * 1.校验mac地址开关
     * 2.判断是否有匹配的mac地址
     */
    private void checkAPMacEnable() {
        showPgDlg("正在校验MAC...");
        new QueryMacNetRequest().setDeptCode(checkBreakCardEntity.getDestDeptCode()).checkAPMacEnable(this, new QueryMacUICallBack() {
            @Override
            public void onError(String msg) {
                dismissPgDlg();
                if (msg != null) {
                    showToast(msg);
                }
            }

            @Override
            public void onSuccess() {
                breakCardExec();
            }
        });
    }

    /**
     * 执行打卡方法
     */
    private void breakCardExec() {
        if (checkBreakCardEntity.getBreakTime() != null && !"".equals(checkBreakCardEntity.getBreakTime())
                || checkBreakCardEntity.getArriveTime() != null && !"".equals(checkBreakCardEntity.getArriveTime())) {
            dismissPgDlg();
            showToast("已打卡！");
            SoundVibratorManager.playSound(2);
            return;
        }

        showPgDlg("正在打卡...");
        BreakCardRequest breakCardRequest = new BreakCardRequest();
        breakCardRequest.setTaskType(1);
        breakCardRequest.setDataSource(3);
        breakCardRequest.setStowageNo(checkBreakCardEntity.getStowageNo());
        breakCardRequest.setClockType(CLOCK_TYPT);
        breakCardRequest.setDeptCode(sharedPreferUtil.getDeptCode());
        breakCardRequest.setRelatDeptCode(checkBreakCardEntity.getDestDeptCode());
        breakCardRequest.setPuncherCode(sharedPreferUtil.getValue(Common.USER_CODE));
        breakCardRequest.setPuncherName(sharedPreferUtil.getEmpName());
        //设备mac地址
        breakCardRequest.setColumn1(NetworkUtil.getMacAddr());
        //打卡时间
        breakCardRequest.setStrClockTime(DateHelper.getDateTimeFormate(new Date()));

        String url = "";
        if (Common.BREAK_CARD_SWITCH == 1) {
            url = Constants.URL_CAR_CLOCK_FOR_PDA;
        } else {
            url = Constants.URL_VMS_CAR_COLCK;
        }

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(JiaoJianBreakCardResponse.class)
                .setUrl(url)
                .setRequestObject(breakCardRequest)
                .setConnTimeOut(5L * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        if (obj instanceof JiaoJianBreakCardResponse) {
                            JiaoJianBreakCardResponse response = (JiaoJianBreakCardResponse) obj;
                            if (response.isSuccess()) {
                                showToast("打卡成功！");
                                SoundVibratorManager.playSound(1);
                                try {
                                    //获取打卡时间
                                    String breakDateTime = DateHelper.formatTimeEight(response.getData());
                                    Date dateTime = DateHelper.getDateTime(breakDateTime);
                                    String breakDate = DateHelper.getDateFormate(dateTime);
                                    String breakTime = DateHelper.getDateFormateHHMM(dateTime);
                                    String timeSeq = DateHelper.getDateTimeFormateForSimple(dateTime);
                                    checkBreakCardEntity.setBreakTime(breakTime);
                                    checkBreakCardEntity.setTimeSeq(timeSeq);
                                    checkBreakCardEntity.setCheck(false);
                                    checkBreakCardEntity.setBreakDate(breakDate);
                                    //按照时间降序
                                    Collections.sort(mStowagesEntities);
                                    mAdapter.notifyDataSetChanged();
                                    //保存打卡数据
                                    saveBreakDate(checkBreakCardEntity, breakDateTime, breakTime, breakDate);
                                } catch (Exception e) {
                                    LogUtil.e(e.toString());
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 保存打卡数据
     */
    private void saveBreakDate(JiaoJianBreakCardEntity jiaoJianBreakCardEntity, String breakDateTiem, String breakTime, String breakDate) {
        BreakCardTable breakCardTable = new BreakCardTable();
        breakCardTable.setStowageNo(jiaoJianBreakCardEntity.getStowageNo());
        breakCardTable.setClockType(CLOCK_TYPT);
        breakCardTable.setDeptCode(sharedPreferUtil.getDeptCode());
        breakCardTable.setRelatDeptCode(jiaoJianBreakCardEntity.getDestDeptCode());
        breakCardTable.setPuncherCode(sharedPreferUtil.getWorkNum());
        breakCardTable.setPuncherName(sharedPreferUtil.getEmpName());
        breakCardTable.setClockDateTime(breakDateTiem);
        breakCardTable.setClockTime(breakTime);
        breakCardTable.setTimeSeq(jiaoJianBreakCardEntity.getTimeSeq());
        breakCardTable.setClockDate(breakDate);
        try {
            breakCardTableDao.insert(breakCardTable);
        } catch (SQLException e) {
            LogUtil.e(e.toString());
        }
    }

    @Override
    public boolean showBack() {
        return true;
    }

    @Override
    public void setBack() {
        finish();
    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

}
